package cn.source.web.controller.tool;

import cn.source.common.config.RuoYiConfig;
import cn.source.common.core.controller.BaseController;
import cn.source.system.domain.GkZytb;
import cn.source.system.domain.GkZytbDetail;
import cn.source.system.service.IGkZytbDetailService;
import cn.source.system.service.IGkZytbService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/download")
public class DownLoadController extends BaseController{

    @Autowired
    private IGkZytbService gkZytbService;

    @Autowired
    private IGkZytbDetailService gkZytbDetailService;


    @GetMapping("/mntbExport")
    public void mntbExport(String userId, HttpServletResponse response, HttpServletRequest request) throws Exception
    {
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        OutputStream out = null;
        try {
            HSSFSheet hssfSheet = hssfWorkbook.createSheet("sheet");


            CellStyle cellStyle = hssfWorkbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setBorderBottom(BorderStyle.THIN);
            cellStyle.setBorderLeft(BorderStyle.THIN);
            cellStyle.setBorderRight(BorderStyle.THIN);
            cellStyle.setBorderTop(BorderStyle.THIN);
            cellStyle.setBottomBorderColor((short)1);

            CellStyle cellStyleTop = hssfWorkbook.createCellStyle();
            cellStyleTop.setAlignment(HorizontalAlignment.CENTER);
            cellStyleTop.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyleTop.setBorderBottom(BorderStyle.THIN);
            cellStyleTop.setBorderLeft(BorderStyle.THIN);
            cellStyleTop.setBorderRight(BorderStyle.THIN);
            cellStyleTop.setBorderTop(BorderStyle.THIN);
            cellStyleTop.setBottomBorderColor((short)1);
            cellStyleTop.setLeftBorderColor((short)1);
            cellStyleTop.setRightBorderColor((short)1);


            CellStyle cellStyleLeft = hssfWorkbook.createCellStyle();
            cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
            cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyleLeft.setBorderBottom(BorderStyle.THIN);
            cellStyleLeft.setBorderLeft(BorderStyle.THIN);
            cellStyleLeft.setBorderRight(BorderStyle.THIN);
            cellStyleLeft.setBorderTop(BorderStyle.THIN);
            cellStyleLeft.setBottomBorderColor((short)1);



            CellStyle cellStyleChangeRows = hssfWorkbook.createCellStyle();
            cellStyleChangeRows.setAlignment(HorizontalAlignment.LEFT);
            cellStyleChangeRows.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyleChangeRows.setBorderBottom(BorderStyle.THIN);
            cellStyleChangeRows.setBorderLeft(BorderStyle.THIN);
            cellStyleChangeRows.setBorderRight(BorderStyle.THIN);
            cellStyleChangeRows.setBorderTop(BorderStyle.THIN);
            cellStyleChangeRows.setBottomBorderColor((short)1);
            cellStyleChangeRows.setWrapText(true);

            CellStyle cellStyleTopBorder = hssfWorkbook.createCellStyle();
            cellStyleTopBorder.setAlignment(HorizontalAlignment.CENTER);
            cellStyleTopBorder.setVerticalAlignment(VerticalAlignment.CENTER);

            cellStyleTopBorder.setBorderTop(BorderStyle.THIN);
            cellStyleTopBorder.setBottomBorderColor((short)1);

            String downloadFileName = "";
            StringBuffer downloadFileBuffer = new StringBuffer();
            downloadFileBuffer.append(userId);
            downloadFileBuffer.append(".xls");
            downloadFileName=downloadFileBuffer.toString();

            //	第一行
            HSSFRow row = hssfSheet.createRow(0);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("志愿");
            cell.setCellStyle(cellStyle);


            HSSFCell cell1_1 = row.createCell(1);
            cell1_1.setCellValue("省市");
            cell1_1.setCellStyle(cellStyle);
            //hssfSheet.setColumnWidth(1, 6000);

            HSSFCell cell1_2 = row.createCell(2);
            cell1_2.setCellValue("院校代码");
            cell1_2.setCellStyle(cellStyle);
            hssfSheet.setColumnWidth(2, 4000);

            HSSFCell cell1_3 = row.createCell(3);
            cell1_3.setCellValue("院校名称");
            cell1_3.setCellStyle(cellStyle);
            hssfSheet.setColumnWidth(3, 4000);

            HSSFCell cell1_4 = row.createCell(4);
            cell1_4.setCellValue("全国排名");
            cell1_4.setCellStyle(cellStyle);

            HSSFCell cell1_5 = row.createCell(5);
            cell1_5.setCellValue("专业组");
            cell1_5.setCellStyle(cellStyle);

            HSSFCell cell1_6 = row.createCell(6);
            cell1_6.setCellValue("投档概率");
            cell1_6.setCellStyle(cellStyle);

            HSSFCell cell1_7 = row.createCell(7);
            cell1_7.setCellValue("招生计划数");
            cell1_7.setCellStyle(cellStyle);
            hssfSheet.setColumnWidth(7, 4000);

            HSSFCell cell1_8 = row.createCell(8);
            cell1_8.setCellValue("专业代码");
            cell1_8.setCellStyle(cellStyle);

            HSSFCell cell1_9 = row.createCell(9);
            cell1_9.setCellValue("专业名称");
            cell1_9.setCellStyle(cellStyle);

            HSSFCell cell1_10 = row.createCell(10);
            cell1_10.setCellValue("专业排名");
            cell1_10.setCellStyle(cellStyle);
            hssfSheet.setColumnWidth(10, 4000);

            HSSFCell cell1_11 = row.createCell(11);
            cell1_11.setCellValue("专业招生数");
            cell1_11.setCellStyle(cellStyle);
            hssfSheet.setColumnWidth(11, 4000);

            HSSFCell cell1_12 = row.createCell(12);
            cell1_12.setCellValue("专业录取概率");
            cell1_12.setCellStyle(cellStyle);
            hssfSheet.setColumnWidth(12, 4000);


            GkZytb zytb=new GkZytb();
            zytb.setMemberId(userId);
            List<GkZytb> list=gkZytbService.selectGkZytbList(zytb);
            if(list.size()>0) {//已经填写了志愿，可以下载


                //查询模拟填报详情列表
                GkZytbDetail gkZytbDetail=new GkZytbDetail();
                gkZytbDetail.setUserId(userId);
                List<GkZytbDetail> detailList=gkZytbDetailService.selectGkZytbDetailList(gkZytbDetail);

                int sheetRow=1;
                for(int i=0;i<list.size();i++){
                    GkZytb gkzytb=list.get(i);

                    int rowFirst=sheetRow;

                    int rowspan=0;
                    for(int j=0;j<detailList.size();j++){
                        GkZytbDetail detail=detailList.get(j);
                        if(gkzytb.getId().equals(detail.getGkZytbId())){
                            rowspan++;
                        }
                    }


                    //本志愿第一行
                    int trSeq=0;
                    for(int j=0;j<detailList.size();j++){
                        GkZytbDetail detail=detailList.get(j);
                        if(gkzytb.getId().equals(detail.getGkZytbId())){
                            if(trSeq==0){//插入志愿行

                                HSSFRow row2 = hssfSheet.createRow(sheetRow);
                                HSSFCell cell2 = row2.createCell(0);
                                cell2.setCellValue("第"+gkzytb.getZyseq()+"志愿");
                                cell2.setCellStyle(cellStyle);


                                HSSFCell cell2_1 = row2.createCell(1);
                                cell2_1.setCellValue(gkzytb.getProvinceName());
                                cell2_1.setCellStyle(cellStyle);

                                HSSFCell cell2_2 = row2.createCell(2);
                                cell2_2.setCellValue(gkzytb.getSchoolCode());
                                cell2_2.setCellStyle(cellStyle);
                                hssfSheet.setColumnWidth(2, 4000);

                                HSSFCell cell2_3 = row2.createCell(3);
                                cell2_3.setCellValue(gkzytb.getSchoolName());
                                cell2_3.setCellStyle(cellStyle);
                                hssfSheet.setColumnWidth(3, 4000);

                                HSSFCell cell2_4 = row2.createCell(4);
                                cell2_4.setCellValue(gkzytb.getQgRank());
                                cell2_4.setCellStyle(cellStyle);

                                HSSFCell cell2_5 = row2.createCell(5);
                                cell2_5.setCellValue(gkzytb.getZyzCode());
                                cell2_5.setCellStyle(cellStyle);

                                HSSFCell cell2_6 = row2.createCell(6);
                                cell2_6.setCellValue(gkzytb.getRateSumit());
                                cell2_6.setCellStyle(cellStyle);

                                HSSFCell cell2_7 = row2.createCell(7);
                                cell2_7.setCellValue(gkzytb.getPlanNums());
                                cell2_7.setCellStyle(cellStyle);

                                HSSFCell cell2_8 = row2.createCell(8);
                                cell2_8.setCellValue(detail.getMajorCode());
                                cell2_8.setCellStyle(cellStyle);

                                HSSFCell cell2_9 = row2.createCell(9);
                                cell2_9.setCellValue(detail.getMajorName());
                                cell2_9.setCellStyle(cellStyle);

                                HSSFCell cell2_10 = row2.createCell(10);
                                cell2_10.setCellValue(detail.getMajorPm());
                                cell2_10.setCellStyle(cellStyle);

                                HSSFCell cell2_11 = row2.createCell(11);
                                cell2_11.setCellValue(detail.getPlanNums());
                                cell2_11.setCellStyle(cellStyle);

                                HSSFCell cell2_12 = row2.createCell(12);
                                cell2_12.setCellValue(detail.getRateSubmit());
                                cell2_12.setCellStyle(cellStyle);
                            }else {//插入专业行
                                HSSFRow row2 = hssfSheet.createRow(sheetRow);

                                HSSFCell cell2_8 = row2.createCell(8);
                                cell2_8.setCellValue(detail.getMajorCode());
                                cell2_8.setCellStyle(cellStyle);

                                HSSFCell cell2_9 = row2.createCell(9);
                                cell2_9.setCellValue(detail.getMajorName());
                                cell2_9.setCellStyle(cellStyle);

                                HSSFCell cell2_10 = row2.createCell(10);
                                cell2_10.setCellValue(detail.getMajorPm());
                                cell2_10.setCellStyle(cellStyle);

                                HSSFCell cell2_11 = row2.createCell(11);
                                cell2_11.setCellValue(detail.getPlanNums());
                                cell2_11.setCellStyle(cellStyle);

                                HSSFCell cell2_12 = row2.createCell(12);
                                cell2_12.setCellValue(detail.getRateSubmit());
                                cell2_12.setCellStyle(cellStyle);

                            }

                            trSeq++;

                            sheetRow++;

                            //rowspan++;
                        }
                    }

                    //合并单元格

                    System.out.println("--------rowFirst--"+rowFirst+"------rowspan-------"+rowspan);
                    /*
                    hssfSheet.addMergedRegion(new CellRangeAddress(rowFirst, rowFirst+rowspan, 0, 0));//	标题

                    hssfSheet.addMergedRegion(new CellRangeAddress(rowFirst, rowFirst+rowspan, 1, 1));//	标题
                    hssfSheet.addMergedRegion(new CellRangeAddress(rowFirst, rowFirst+rowspan, 2, 2));//	标题
                    hssfSheet.addMergedRegion(new CellRangeAddress(rowFirst, rowFirst+rowspan, 3, 3));//	标题
                    hssfSheet.addMergedRegion(new CellRangeAddress(rowFirst, rowFirst+rowspan, 4, 4));//	标题
                    hssfSheet.addMergedRegion(new CellRangeAddress(rowFirst, rowFirst+rowspan, 5, 5));//	标题
                    hssfSheet.addMergedRegion(new CellRangeAddress(rowFirst, rowFirst+rowspan, 6, 6));//	标题
                    hssfSheet.addMergedRegion(new CellRangeAddress(rowFirst, rowFirst+rowspan, 7, 7));//	标题
                    **/

                }
                //插入最后一行空白行
                HSSFRow row2 = hssfSheet.createRow(sheetRow);
                for(int i=0;i<=12;i++){
                    HSSFCell cell2_12 = row2.createCell(i);
                    cell2_12.setCellValue("");
                    cell2_12.setCellStyle(cellStyleTop);
                }
            }


            out = new FileOutputStream(getAbsoluteFile(downloadFileName));
            hssfWorkbook.write(out);

            String filepath=RuoYiConfig.getDownloadPath() + "/"+downloadFileName;

            try {
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(filepath));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();

                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadFileName,"UTF-8"));
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }finally{
	        	/*
	            try {
	                File f = new File(filepath);
	                f.delete();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	            */
            }



        } catch (Exception e) {
            e.printStackTrace();
            logger.error("导出Excel异常{}", e.getMessage());

        }
        finally
        {
            if (hssfWorkbook != null)
            {
                try
                {
                    hssfWorkbook.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (out != null)
            {
                try
                {
                    out.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    public String getAbsoluteFile(String filename)
    {
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }
}
